package com.cloudauth.authgateway.filter;

import io.jsonwebtoken.Jwt;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        Route gateWayUrl = exchange.getRequiredAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);

        URI uri = gateWayUrl.getUri();

        ServerHttpRequest request = exchange.getRequest();

        HttpHeaders headers = request.getHeaders();


        String token = headers.getFirst(JwtUtil.HEADER_AUTH);

        //TODO
        Map<String, String> parseTokenInfo = JwtUtil.validateToken(token, "");

        ServerHttpRequest.Builder mutate = request.mutate();

        //此处代码仅限于demo 测试使用
        if ("admin".equals(parseTokenInfo.get("user"))
                    || "spring".equals(parseTokenInfo.get("user"))
                    || "cloud".equals(parseTokenInfo.get("user"))){
                mutate.header("x-user-id",parseTokenInfo.get("id"));
                mutate.header("x-user-name",parseTokenInfo.get("user"));
                mutate.header("x-user-serviceName",uri.getHost());
        }else {
            throw new PermissionException("user not exist, please check");
        }

        ServerHttpRequest build = mutate.build();
        return chain.filter(exchange.mutate().request(build).build());
    }
}
